/*
 * P2696.cpp
Description

For any integers p and q with q > 0, define p mod q to be the integer r with 0 <= r <= q −1 such that p−r is divisible by q. For example, we have
109 mod 10 = 9
−7 mod 3 = 2
−56 mod 7 = 0

Let Φ be a function defined recursively as follows.

where a, b, c, d, e, f, g, h are integers with 0 < a, b, c, d, e, f, g, h <= 1000. One can easily see that 0 <= Φ(i) <= 1000 holds for any integer i >= 0. Now for any given integers a, b, c, d, e, f, g, h, i with 0 < a, b, c, d, e, f, g, h, i <= 1000, you are asked to write a program to output

Φ(i). (Hint: a direct recursive implementation of the above recurrence

relation is likely to run forever for large i.)
Input

The first line contains the number n of test cases. Each of the following n lines contains the sequence a, b, c, d, e, f, g, h, i of integers.
Output

For each test case, your program has to output the correct value of Φ(i).
Sample Input

3
1 2 3 4 5 6 7 8 9
11 12 13 14 15 16 17 18 19
321 322 323 324 325 326 327 328 329

Sample Output

4
0
90
 */

#include<iostream>
using namespace std;

int mod(int p,int q){
	int i=0;
	while((p-i)%q!=0){
		i++;
	}
	return i;
}

int main(){
	int a,b,c,d,e,f,g,h,i,testcase,t;
	int res[1001];
	scanf("%d",&testcase);
	while(testcase>0){
		testcase--;
		scanf("%d%d%d%d%d%d%d%d%d",&a,&b,&c,&d,&e,&f,&g,&h,&i);
		res[0]=a;
		res[1]=b;
		res[2]=c;
		for(t=3;t<=i;t++){
			if(t%2==0){
				res[t]=mod((f*res[t-1]-d*res[t-2]+e*res[t-3]),h);
			}else{
				res[t]=mod((d*res[t-1]+e*res[t-2]-f*res[t-3]),g);
			}
		}
		printf("%d\n",res[i]);
	}

	return 0;
}



